-1

I've been trying to print out and HTTP post using Swift for a mobile app, I am able to log it with javascript and express.js. But when using the server created with Go it's giving me:

Get "http://192.121.1.397:8080": dial tcp http://192.121.1.397:8080: i/o timeout
exit status 1

below you can see the code for all 3 languages:

Swift:

import Foundation


class Service: NSObject {
    static let shared = Service()
    
    func fetch(completion: @escaping (Result<[Post], Error>) -> ()){
        guard let url = URL(string: "http://192.121.1.397:8080" ) else{return}
        
        URLSession.shared.dataTask(with: url) { (data, resp, err) in
            if let err = err {
                print(err)
                return
            }
            
            guard let data = data else {return}
            
            do{
                let posts = try JSONDecoder().decode([Post].self, from:data)
                completion(.success(posts))
            } catch{
                completion(.failure(error))
            }
        }
    }
    func post(title: String, body: String, completion: @escaping (Error?) -> ())  {
        guard let url = URL(string: "http://192.168.1.148:8080") else{return}
        var urlReq = URLRequest(url:url)
        urlReq.httpMethod = "POST"
        
        let params = ["title": title, "postBody": body]
        
        do{
            let data = try JSONSerialization.data(withJSONObject: params, options: .init())
            
            urlReq.httpBody = data
            urlReq.setValue("application/json", forHTTPHeaderField: "Content-Type")
            
            URLSession.shared.dataTask(with: urlReq){(data, resp, err) in
                guard let data = data else{return}
                completion(nil)
            }.resume()
        } catch{
            completion(error)
        }
    }
}

and its called in a @obj func on a different file:

 @objc func ButtonClicked(sender: UIButton)->Void{
      
     
        
      sceneView.allowsCameraControl  = false

        
        if(buttonsArray[sender.tag].nav == false){
        
            if(buttonsArray[sender.tag].name == "News"){
                Service.shared.post(title:"rodo" , body:"aya"){
                    (err) in
                    if let err = err{
                        print(err)
                        return
                    }
                    print("posted")
                }
}

Golang code:

package main

import (
    "fmt"
    "os"
    "io/ioutil"
    "log"
    "net/http"
)


func main() {
    http.HandleFunc("/", HelloServer) // deal
    http.ListenAndServe(":8080", nil)
   
}

func HelloServer(w http.ResponseWriter, r *http.Request) {
    // fmt.Fprintf(w, "Hello, lol") // post

    resp, err := http.Get("http://http://192.121.1.397:8080") //https://api.github.com/repos/dotcloud/docker

if err != nil{
    fmt.Println("now")
    log.Fatal(err)
}

defer resp.Body.Close()

body, err := ioutil.ReadAll(resp.Body)

if err != nil{
    fmt.Println("here")
    log.Fatal(err)
}

_, err = os.Stdout.Write(body)
// _, err = fmt.Println(string(body))

if err != nil{
    fmt.Println("There")
    log.Fatal(err)
}
}

Javascript server which can read the post:

const express = require('express')
const app = express()
var bodyParser = require('body-parser')
const port = process.env.PORT || 8080
;
app.use(bodyParser.urlencoded({ extended: true }))

// parse application/json
app.use(bodyParser.json())


app.get('/', (req, res) => {
    res.send({ express: 'YOUR EXPRESS BACKEND IS CONNECTED TO REACT' })
   
}
)


app.post('/', function(req, res) {
    var parsedBody = req.body;
    console.log(parsedBody)
    res.send({ express: 'YOUR EXPRESS BACKEND IS CONNECTED TO REACT' })

 });




app.listen(port, () => console.log(`Example app listening on port ${port}!`))

Thank you for your time

Camille Basbous
  • 299
  • 5
  • 11
  • 34

1 Answers1

2

.... http.Get("http://http://192.121.1.397:8080")

This is no valid URL. It should be only http://192.121.1.397:8080.

Apart from that I'm not really sure what you are doing. Why do you try to access the server in the handler of the same server? This is also different from what you are doing within nodejs, where you just send a simply response.

Steffen Ullrich
  • 114,247
  • 10
  • 131
  • 172