2 http 服务
官方文档说http这里是在net/http原生包的基础上做了修改。
官方给的案例:
go
package main
import (
"net/http"
"github.com/TarsCloud/TarsGo/tars"
)
func main() {
mux := &tars.TarsHttpMux{}
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello tafgo"))
})
cfg := tars.GetServerConfig()
tars.AddHttpServant(mux, cfg.App+"."+cfg.Server+".HttpObj") //Register http server
tars.Run()
}
可以看到 在初始化了TarsHttpMux
, 再将TarsHttpMux
注册到tars框架中作为servant就可以启动http服务。
-
TarsHttpMux
是什么:go// TarsHttpMux is http.ServeMux for tars http server. type TarsHttpMux struct { http.ServeMux cfg *TarsHttpConf }
可以看出
TarsHttpMux
确实就只是对http.ServeMux
做了个包装加入了Conf
并加入了上报状态信息、计算耗时等基本服务器功能。 -
将
TarsHttpMux
注册到tars框架中作为servant
:-
tars.AddHttpServant
的底层实现函数如下:
go// AddHttpServantWithExceptionStatusChecker add http servant handler with exceptionStatusChecker for obj. func (a *application) AddHttpServantWithExceptionStatusChecker(mux HttpHandler, obj string, exceptionStatusChecker func(int) bool) { cfg, ok := a.tarsConfig[obj] if !ok { msg := fmt.Sprintf("http servant obj name not found: %s", obj) ReportNotifyInfo(NotifyError, msg) TLOG.Debug(msg) panic(errors.New(msg)) } TLOG.Debugf("add http protocol server: %+v", cfg) a.objRunList = append(a.objRunList, obj) addrInfo := strings.SplitN(cfg.Address, ":", 2) var port int64 if len(addrInfo) == 2 { var err error port, err = strconv.ParseInt(addrInfo[1], 10, 32) if err != nil { panic(fmt.Errorf("http server listen port: %s parse err: %v", addrInfo[1], err)) } } svrCfg := a.ServerConfig() httpConf := &TarsHttpConf{ Container: svrCfg.Container, AppName: fmt.Sprintf("%s.%s", svrCfg.App, svrCfg.Server), Version: svrCfg.Version, IP: addrInfo[0], Port: int32(port), SetId: svrCfg.Setdivision, ExceptionStatusChecker: exceptionStatusChecker, } mux.SetConfig(httpConf) s := &http.Server{Addr: cfg.Address, Handler: mux, TLSConfig: cfg.TlsConfig} a.httpSvrs[obj] = s }
- 简单来说就是将http根据配置实例化-》再注册Sever-》这代码很好理解
-
-
配置文件配置servant
xml<tars> <application> <server> <AiGo.backend.HttpObjAdapter> allow endpoint=http -h 127.0.0.1 -p 18080 -t 60000 handlegroup=AiGo.backend.HttpObjAdapter maxconns=200000 protocol=http queuecap=10000 queuetimeout=60000 servant=AiGo.backend.HttpObj shmcap=0 shmkey=0 threads=1 </AiGo.backend.HttpObjAdapter> </server> </application> </tars>
可以看出就
protocol=http
这里改了,其他的和tars服务没啥区别。