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

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()
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?