doukengsha9472 2015-11-04 13:21
浏览 70

Golang连接到angularjs

How do I connect a backend server in go lang to angularjs? I know angularjs communicates with go via $http or $resource services but what part of the go code links communicates with angular once all the data structs have been made? Would this be the encoded/marshalled json or do we create some kind of route...

I am a newbie looking to start this project after studying angular and go but this is the part i don't understand - what is the end point from go that angulars $resource or $http service links with?

  • 写回答

1条回答 默认 最新

  • dongyan4424 2015-11-05 10:22
    关注

    Create a http endpoint that reads json string, unmarshalls it, does some logic with it and writes a json string to the response. E.g:

    func main() {
    
    http.HandleFunc("/api/", apiHandler)
    
        logInfo(fmt.Sprintf("Starting server on port %d", serverPort))
        err := http.ListenAndServe(fmt.Sprintf(":%d", serverPort), nil)
        if err != nil {
            logError(err)
        }
    }
    
    
    func apiHandler(w http.ResponseWriter, r *http.Request) {
    
        //ensure its a post
        method := r.Method
    
        if method != "POST" {
            fail(w, "Invalid http method")
            return
        }
    
        requestData, err := ioutil.ReadAll(r.Body)
    
        if err != nil {
            fail(w, err.Error())
            return
        }
    
    
        respData, err := doBusinessLogicWithData(requestData)
    
        if err != nil {
            fail(w, err.Error())
            return
        }
    
        respJSONBytes, err := json.Marshal(respData)
        if err != nil {
            fail(w, err.Error())
            return
        }
        fmt.Fprintln(w, string(respJSONBytes))
    
    }
    
    func fail(w http.ResponseWriter, message string) {
    
        result := &struct {
            Success bool
            Message string
        }{
            Success: false,
            Message: message,
        }
    
        resultJSONBytes, err := json.Marshal(result)
        if err != nil {
            logError(err)
            fmt.Fprintln(w, "Unable to generate result")
            return
        }
        fmt.Fprintln(w, string(resultJSONBytes))
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘