Answer the question
In order to leave comments, you need to log in
How to implement your API on a domain?
There is a golang code that listens on port ****, but you can only access it using the machine's IP. Can I make it so that I can access my domain? Instead of ip:port/user/1 domain.com/user/1
package main
import (
"fmt"
"github.com/gorilla/mux"
"io/ioutil"
"math/rand"
"net/http"
"os"
"strings"
"time"
)
func main() {
router := mux.NewRouter()
router.HandleFunc("/save/{text}", AppendText)
http.Handle("/", router)
http.ListenAndServe(":1234", nil)
}
func AppendText(w http.ResponseWriter, r *http.Request){
w.Header().Set("Access-Control-Allow-Origin", "*")
vars := mux.Vars(r)
f, err := os.OpenFile("file.txt", os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
panic(err)
}
defer f.Close()
if _, err = f.WriteString(vars["text"] + "\n"); err != nil {
panic(err)
}
}
Answer the question
In order to leave comments, you need to log in
Can.
Register a domain and enter the IP of your server in its settings.
Next, you have two options.
If you have only one service on the server, you can immediately listen to port 80, instead of 1234.
And it will work.
If there are a lot of domains on the server -
- install a web server, for example nginx, which listens on port 80 on your IP
- set up a virtual host in nginx for the domain you need and prescribe there so that requests are redirected to your service IP: port (1234)
server {
listen *:80;
server_name тут_ваш_домен;
location / {
proxy_pass http://тут_ip_вашего_сервиса:1234;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question