Go语言实战流媒体视频网站(3.6)

719 阅读1分钟

api之http handler层

总览:

api
    │  handlers.go
    │  main.go
    │  response.go
    │
    ├─dbops
    │      api.go
    │
    └─defs
            apidef.go
            errs.go

流程:

handler->validation{1.request, 2.user}->business logic->response

  1. data model.
  2. error handing.

handler.go会调用dbops, 拿到它想要的东西, 然后做进一步处理, 处理包括消息/信息的定义, 然后将它们一起组装成response, 最后调取response.go, response返回结果到handler.go, 最后输出.

handlers.go

package main

import (
	"github.com/julienschmidt/httprouter"
	"io"
	"net/http"
)

func CreateUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	io.WriteString(w, "Create User Handler")
}

func Login(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	uname := p.ByName("username")
	io.WriteString(w, uname)
}

apidef.go 接受用户名和密码

package defs

type UserCredential struct {
	Username string `json:"username"`
	Pwd string `json:"pwd"`
}

--------------------------------------------
`json`go里打tag的一种方式,会产生下面的结构
{
	Username:xxx
	Pwd:xxx
}

errs.go 错误返回

package defs

type Err struct {
	Error string `json:"error"`
	ErrorCode string `json:"error_code"`
}

type ErrResponse struct {
	HttpSC int
	Erros Err
}

var (
	ErrorRequestBodyParseFailed = ErrResponse{HttpSC: 400, Error:Err{Error:"Request body is not correct", ErrorCode:"001"}}
	ErrorNotAuthUser = ErrResponse{HttpSC: 401, Error:Err{Error:"User authentical faild", ErrorCode:"002"}}
)

dpops/api.go 连接数据库并操作

package dbops

import (
	"database/sql"
)

func openConn() *sql.DB {

}

func AddUserCredential(loginName string, pwd string) error {

}

func GetUserCredential(loginName string ) (string, error)  {

}

response.go 根据处理结果返回相应的response

package main

import (
	//"io"
	"net/http"
)

func sendErrorResponse(w http.ResponseWriter){

}

func sendNormalResponse(w http.ResponseWriter)  {

}