Last active
November 6, 2018 14:11
-
-
Save binary4cat/4f0b0a87c1b289b1fe079a44d121f6c1 to your computer and use it in GitHub Desktop.
Go HTTP接口简单例子
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"log" | |
"net/http" | |
) | |
type UserInfo struct { | |
Email string `json:"email"` | |
Password string `json:"password"` | |
} | |
func main() { | |
http.HandleFunc("/api/login", loginFunc) | |
http.HandleFunc("/api/get", getUserInfo) | |
http.HandleFunc("/", index) | |
log.Fatal("启动服务失败:", http.ListenAndServe(":2333", nil)) | |
} | |
func loginFunc(w http.ResponseWriter, r *http.Request) { | |
setupResponse(&w, r) | |
if (*r).Method == "OPTIONS" { | |
return | |
} | |
decoder := json.NewDecoder(r.Body) | |
res := false | |
reqData := UserInfo{} | |
decoder.Decode(&reqData) | |
if reqData.Email != "" && reqData.Password != "" { | |
res = true | |
} | |
fmt.Fprintf(w, "%v", res) | |
} | |
func getUserInfo(w http.ResponseWriter, r *http.Request) { | |
setupResponse(&w, r) | |
if (*r).Method == "OPTIONS" { | |
return | |
} | |
resData := UserInfo{"123@qq.com", "123123"} | |
j, _ := json.Marshal(resData) | |
w.Header().Set("Content-Type", "application/json") | |
w.Write(j) | |
} | |
func index(w http.ResponseWriter, r *http.Request) { | |
setupResponse(&w, r) | |
if (*r).Method == "OPTIONS" { | |
return | |
} | |
fmt.Fprintf(w, "Hello golang http!") | |
} | |
// 允许跨域请求 | |
func setupResponse(w *http.ResponseWriter, r *http.Request) { | |
(*w).Header().Set("Access-Control-Allow-Origin", "*") | |
(*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE") | |
(*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment