TarsCloud / TarsGo

A high performance microservice framework in golang. A linux foundation project.
BSD 3-Clause "New" or "Revised" License
3.31k stars 508 forks source link

TarsGo Can not implement RESTful API #190

Closed somnmos closed 4 years ago

somnmos commented 4 years ago

I found TarsGo Use the http package to dispatch request, but the http package can not implement RESTfull API. I want to make a integration with "github.com/gin-gonic/gin" or "github.com/julienschmidt/httprouter", did you have some other suggestion.

defool commented 4 years ago

Of course it is easy to be integrated with some web frameworks. Here is an example:

package main

import (
    "fmt"
    "net/http"

    "github.com/TarsCloud/TarsGo/tars"
    "github.com/gorilla/mux"
)

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
        fmt.Fprintf(w, "Home")
    })
    r.HandleFunc("/products/{key}", func(w http.ResponseWriter, r *http.Request) {
        vars := mux.Vars(r)
        w.WriteHeader(http.StatusOK)
        fmt.Fprintf(w, "product: %v\n", vars["key"])
    })

    cfg := tars.GetServerConfig()
    tarsMux := tars.TarsHttpMux{}
    tarsMux.Handle("/", r)
    tars.AddHttpServant(&tarsMux, cfg.App+"."+cfg.Server+".MainObj") // use  `not TARS` protocol

    tars.Run()
}