dqpfkzu360216 2017-03-18 20:37
浏览 300
已采纳

Golang-没有选择器的软件包用户

Please, I searched this a lot and after not been able to find, I am writing and not that I didn't try to search all over first. Couldn't get the right answer. I even tried to check Revel's function and couldn't get the answer from there as well.

When I run this program I get this error for line

./test.go:11: use of package http without selector

This error points at the line below where I have written

*http

inside the struct

Confusing part is that with test and dot I even get auto complete with VIM. So I don't know why is the error. Is it that it has to be somewhat like

*(net/http)

or something like that ?

package main

import (
    "fmt"
    "net/http"
)

type HandleHTTP struct {
    *http
}

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Path is %s", r.URL.Path[1:])

}

func main() {

    test := HandleHTTP{}

    test.http.HandleFunc("/", handler)
    test.http.ListenAndServe(":8080", nil)

}
  • 写回答

1条回答 默认 最新

  • druzuz321103 2017-03-18 21:42
    关注

    If you want to have two or more instances serving from different ports you need to spin up two, or more, server. Would something like this, perhaps, work for you?

    package main
    
    import (
        "fmt"
        "net/http"
    )
    
    type HandleHTTP struct {
        http *http.Server
    }
    
    func handler(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Path is %s", r.URL.Path[1:])
    
    }
    
    func main() {
        mux1 := http.NewServeMux()
        mux1.HandleFunc("/", handler)
        test1 := HandleHTTP{http:&http.Server{Addr:":8081", Handler:mux1}}
    
        mux2 := http.NewServeMux()
        mux2.HandleFunc("/", handler)
        test2 := HandleHTTP{http:&http.Server{Addr:":8082", Handler:mux2}}
    
        // run the first one in a goroutine so that the second one is executed
        go test1.http.ListenAndServe()
        test2.http.ListenAndServe()
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建