L
L
linuxoid_inrus2020-11-18 11:26:26
go
linuxoid_inrus, 2020-11-18 11:26:26

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

2 answer(s)
E
Evgeny Mamonov, 2020-11-18
@EvgenyMamonov

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)

Example nginx config (virtual host)

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;
    }
}

K
Klars, 2020-11-24
@Klars

a counter question on the code
in the code I see panic ()
Why is it not caught in main through recovery ()? Or is it meant to be?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question